package org.greenrobot.eventbus.annotationprocessor;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.Collection;

import javax.annotation.processing.Filer;
import javax.lang.model.element.Modifier;

/**
 * Created by harryguo on 2018/7/22.
 * 本类用来创建一个class的内容全文
 */
public class AutoRegisterCreator {
    // private TypeElement mTypeElement;
    private Collection<SubscribeClass> mSubscribeClazz;

    AutoRegisterCreator(Collection<SubscribeClass> clazz) {
        mSubscribeClazz = clazz;
    }

    public void createFile(Filer filer, boolean needSetIndexFile) throws IOException {
        if (mSubscribeClazz != null && mSubscribeClazz.size() > 0) {
            String packageName = EventBus.class.getPackage().getName();
            // 带参数eventBus的函数：public static EventBusAutoRegister.register(EventBus eventBus);
            MethodSpec.Builder registerMethod = MethodSpec.methodBuilder(EventBus.METHOD_NAME_AUTO_REGISTER)
                    .addModifiers(Modifier.PUBLIC)
                    .addModifiers(Modifier.STATIC)
                    .addParameter(ClassName.get(EventBus.class), "eventBus")
                    .addJavadoc("This is called by EventBus. When any register is about to run.\n");
            // 添加index
            if (needSetIndexFile) {
                registerMethod.addStatement("eventBus.setSubscribeIndexIfNone(new $N())", packageName + "." + EventBus.CLASS_NAME_INDEX);
            }
            for(SubscribeClass subscribeClass : mSubscribeClazz) {
                // 注册那些静态订阅者所对应的类
                registerMethod.addStatement("eventBus.register($N.class)", subscribeClass.getFullClassName());
            }

            //generate class
            TypeSpec injectedClass = TypeSpec.classBuilder(EventBus.CLASS_NAME_AUTO_REGISTER)
                    .addModifiers(Modifier.PUBLIC)
                    .addMethod(registerMethod.build())
                    .addJavadoc("Copyright (C) 2018-2023 Harry Guo\nAuto generated by EventBus.\n" +
                            "The purpose of this class is to auto register static subscriber.\n")
                    .build();

            JavaFile.builder(packageName, injectedClass).build().writeTo(filer);
        }
    }
}
